import React, { useEffect, useRef, useState } from 'react';
import { Button, Space, Tooltip } from 'antd';
import { CheckOutlined, CopyOutlined } from '@ant-design/icons';
import { ProForm, ProFormSelect } from '@ant-design/pro-components';
import type { ProFormSelectProps } from '@ant-design/pro-form/lib/components/Select';
import './index.less';

const CopyableSelect: React.FC<ProFormSelectProps> = ({
  label,
  hidden,
  placeholder,
  disabled,
  ...rest
}) => {
  const selectRef = React.createRef<any>();
  const [isCopied, setIsCopied] = useState(false);
  const timer = useRef<any>();
  const selectPlaceholder = placeholder ;
  useEffect(() => {
    return () => {
      timer.current && clearTimeout(timer.current);
    };
  }, []);

  return (
    <ProForm.Item
      label={label}
      hidden={hidden}
      style={{ marginBottom: 0 }}
      required={rest.required}
      rules={rest.rules}
    >
      <div ref={selectRef} className="copyable-select">
        <Space.Compact block>
          <ProFormSelect
            formItemProps={{
              className: 'flex-1',
              style: {
                maxWidth: 'calc(100% - 32px)',
              },
            }}
            disabled={disabled}
            placeholder={selectPlaceholder}
            {...rest}
          />
          <Tooltip title="复制">
            <Button
              disabled={disabled}
              icon={isCopied ? <CheckOutlined style={{ color: '#52c41a' }} /> : <CopyOutlined />}
              onClick={() => {
                if (isCopied) return;
                const values = selectRef.current.querySelectorAll('.ant-select-selection-item');
                const valueArr = Array.from(values)
                  .map((item: any) => item.title)
                  .filter((item: string) => {
                    // 如果item是 "+ 5 ..."这种 "+" + " " + "数字" + " " + "..." 的形式，就不要复制
                    const regex = /\+\s\d+\s\.\.\./;
                    return !regex.test(item);
                  });
                const valueText = valueArr.join(',');

                //复制到剪贴板
                const copyEl = document.createElement('input');
                copyEl.setAttribute('value', valueText || (selectPlaceholder as string));
                document.body.appendChild(copyEl);
                copyEl.select();
                document.execCommand('copy');
                document.body.removeChild(copyEl);
                setIsCopied(true);
                timer.current = setTimeout(() => {
                  setIsCopied(false);
                }, 2000);
              }}
            />
          </Tooltip>
        </Space.Compact>
      </div>
    </ProForm.Item>
  );
};

export default CopyableSelect;
